package com.dcy.znoa.service.estate.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dcy.znoa.common.enums.EstateOutnoteStatusCode;
import com.dcy.znoa.common.enums.OperTypeCode;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.DateUtil;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.estate.model.outnote.SelectEstateOutnoteModel;
import com.dcy.znoa.controller.estate.model.outnote.UpdateEstateOutnoteModel;
import com.dcy.znoa.controller.publiz.model.messNotice.AddMessNoticeListAndMsgModel;
import com.dcy.znoa.controller.sys.model.storeFile.AddStoreFileModel;
import com.dcy.znoa.dao.estate.EstateOutnoteMapper;
import com.dcy.znoa.dao.publiz.CompanyDao;
import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.estate.EstateNotice;
import com.dcy.znoa.domain.estate.EstateOutnote;
import com.dcy.znoa.domain.estate.EstateService;
import com.dcy.znoa.domain.publiz.Company;
import com.dcy.znoa.service.estate.EstateOutnoteService;
import com.dcy.znoa.service.publiz.MessNoticeService;
import com.dcy.znoa.service.sys.StoreFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import static com.dcy.znoa.common.util.DateUtil.datetimeFormat_ms;
import static com.dcy.znoa.domain.estate.EstateOutnote.NOT_VALID_QR_CODE;

/**
 * <p>
 * 物业出门条 服务实现类
 * </p>
 *
 * @author cook
 * @since 2018-05-21
 */
@Slf4j
@Service
public class EstateOutnoteServiceImpl extends ServiceImpl<EstateOutnoteMapper, EstateOutnote> implements EstateOutnoteService {

    @Autowired
    EstateOutnoteMapper eoMapper;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    StoreFileService storeFileService;
    @Autowired
    OperDao operDao;
    @Autowired
    MessNoticeService messNoticeService;


    @Override
    public JsonForList selectList(SelectEstateOutnoteModel model) throws InvocationTargetException, IllegalAccessException {
        EstateOutnote cp = new EstateOutnote();
        BeanUtils.copyProperties(cp, model);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<EstateOutnote> list = eoMapper.selectListMapper(model, page);
        return new JsonForList(list, page.getTotal());
    }
    @Transactional
    @Override
    public boolean add(EstateOutnote cp) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        //1 查询出对应的esId receiveOperId
        Long compId = cp.getCompId();
        if (compId == null) {
            throw new BusinessException("404", "登录用户没有归属的企业");
        }
        Company company = companyDao.selectById(compId);
        if (company == null) {
            throw new BusinessException("404", "登录用户没有归属的企业");
        }
        Long esId = company.getEsId();
        if (esId == null) {
            throw new BusinessException("404", "登录用户对应企业没有绑定的物业公司");
        }
        cp.setEsId(esId);
        cp.setStatus(EstateOutnoteStatusCode.NEW.getCode());
        //设置二维码号
        String qrCode = "qr" + DateUtil.getFormatNowDate(datetimeFormat_ms);
        cp.setQrCode(qrCode);
        //查询物业公司对应的管理员
        List<Oper> operList =  operDao.selectList(new EntityWrapper<Oper>().eq(("comp_id"),esId).eq("oper_type", OperTypeCode.PLACEMGR.getCode()));
        if(operList == null || operList.isEmpty()){
            throw new BusinessException("404", "物业公司"+ esId+"没有管理员");
        }
        Long receiveOperId = operList.get(0).getOperId();
        cp.setAuditOperId(receiveOperId);
        boolean result1 = insert(cp);
        if(!result1){
            throw new BusinessException("404", "新增物业出门条失败");
        }
//        //2 操作附件表
//        AddStoreFileModel addStoreFileModel = new AddStoreFileModel();
//        BeanUtils.copyProperties(addStoreFileModel, cp);
//        addStoreFileModel.setEntityTbl("estate_notice");
//        addStoreFileModel.setEntityId(cp.getEsonId());
//        addStoreFileModel.setFileName(addStoreFileModel.getRemoteFileName());
//        addStoreFileModel.setFileFunction(addStoreFileModel.getRemoteFileName());
//        Integer result2 = storeFileService.addBatch(addStoreFileModel);
//        if (result2 == null || result2 <= 0) {
//            throw new BusinessException("404", "新增物业出门条附件失败");
//        }
        //3 发APP内部消息
        AddMessNoticeListAndMsgModel amnlModel = new AddMessNoticeListAndMsgModel();
        log.info("cp.getRemoteFileName() = " + cp.getRemoteFileName());
        BeanUtils.copyProperties(amnlModel, cp);
        log.info("amnlModel.getRemoteFileName() = " + amnlModel.getRemoteFileName());
        String remarkOut = StringUtils.isBlank(cp.getRemark())?"无":cp.getRemark();
        amnlModel.setMessage("出门条物品："+cp.getGoods()+" 备注："+ remarkOut);
        amnlModel.setMessTitle("出门条");
        amnlModel.setCreateOperId(cp.getCreateOperId());
        amnlModel.setOperIdsStr(String.valueOf(receiveOperId));
        amnlModel.setEntityId(cp.getEsonId());
        amnlModel.setEntityTbl("estate_outnote");
        amnlModel.setMessType(4);//4表示物业出门条
        //给接收人的消息
        Long messId = messNoticeService.insertBatchAndMsg(amnlModel);
        if(messId==null||messId<0){
            throw new BusinessException("404", "新增物业服务单-内部消息发送失败");
        }
        return true;
    }
    //一般都要修改状态
    @Transactional
    @Override
    public boolean update(UpdateEstateOutnoteModel model) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        Integer status = model.getStatus();
        if(status==null){//说明没修改状态，那么就不用发消息
            return true;
        }
        EstateOutnote cp = null;
        Date now = new Date();
        Long esonId = model.getEsonId();
        String qrcode =model.getQrCode();
        if(esonId==null && StringUtils.isBlank(qrcode)){
            throw new BusinessException(JsonCommon.NOT_FOUND_MSG,"esonId 和 qrCode 不能同时为空");
        } else if(esonId!=null){
            cp = selectById(model.getEsonId());
        }else{
            EstateOutnote query = new EstateOutnote();
            query.setQrCode(qrcode);
            cp = eoMapper.selectOne(query);
        }
        if(cp == null){
            throw new BusinessException(JsonCommon.NOT_FOUND_MSG,"找不到对应的出门条:esonId = "+ esonId+" qrCode = "+qrcode);
        }
//        log.info(model.toString());
//        log.info(cp.toString());
        //TODO  BeanUtils.copyProperties 有问题，空的也复制过去了  出门条的方式可以温柔一点，不用直接改成 FFFFFF
//        BeanUtils.copyProperties(cp, model);
//        log.info(cp.toString());
        if(cp.getHandleOperId()==null){
            cp.setHandleOperId(model.getHandleOperId());
        }
        cp.setStatus(model.getStatus());
        cp.setUpdateTime(now);
        if(model.getUpdateOperId()!=null){
            cp.setUpdateOperId(model.getUpdateOperId());
        }
        updateById(cp);
        //按状态给不同的人发消息，一般只发内部消息，不发短信
        AddMessNoticeListAndMsgModel amnlModel = new AddMessNoticeListAndMsgModel();
        Long messId = null;
        amnlModel.setCreateOperId(cp.getCreateOperId());
        amnlModel.setOperIdsStr(String.valueOf(cp.getSendOperId()));
        amnlModel.setEntityId(cp.getEsonId());
        amnlModel.setEntityTbl("estate_outnote");
        amnlModel.setMessType(4);//4表示物业出门条
        EstateOutnoteStatusCode estateOutnoteStatusCode = EstateOutnoteStatusCode.getMsgByCode(status);
        switch(estateOutnoteStatusCode){
            case NEW://新增时才为new，这会什么都不需要做
                break;
            case PASSED://通过之后，提示申请人
                amnlModel.setMessage("物业出门条审批成功"+ DateUtil.getFormatNowDate1());
                amnlModel.setMessTitle("物业出门条审批成功");
                messId = messNoticeService.insertBatchAndMsg(amnlModel);
                if(messId==null||messId<0){
                    throw new BusinessException("404", "物业出门条审批发送失败");
                }
                cp.setAuditTime(now);
                break;
            case DONE://完成之后，提示申请人，出门条已使用
                //如果做严格校验的话，应该判断当前用户是不是处理人
                amnlModel.setMessage("物业出门条已使用成功"+ DateUtil.getFormatNowDate1());
                amnlModel.setMessTitle("物业出门条已使用");
                cp.setQrCode(NOT_VALID_QR_CODE);
                messId = messNoticeService.insertBatchAndMsg(amnlModel);
                if(messId==null||messId<0){
                    throw new BusinessException("404", "物业出门条审批发送失败");
                }
                cp.setOutTime(now);
                break;
            case REJECTED://提示申请人
                amnlModel.setMessage("物业出门条审批不成功，备注："+ cp.getRefuseRemark());
                amnlModel.setMessTitle("物业出门条审批被拒绝");
                messId = messNoticeService.insertBatchAndMsg(amnlModel);
                if(messId==null||messId<0){
                    throw new BusinessException("404", "物业出门条审批发送失败");
                }
                cp.setAuditTime(now);
                break;
            case REVOKED://撤销之后，什么都不做
                break;
            default:
                throw new BusinessException("404","status类型有误："+ status);
        }
        return  updateById(cp);
    }

    @Override
    public EstateOutnote selectByEsserId(Long esonId) {
        SelectEstateOutnoteModel model = new SelectEstateOutnoteModel();
        model.setEsonId(esonId);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<EstateOutnote> list =  eoMapper.selectListMapper(model,page);
        if(list!=null && list.size()>0){
            return list.get(0);
        }
        return null;
    }


}
